using System;
using System.Windows.Forms;
using Jbe.TestSuite.Infrastructure.Library;
using Microsoft.Practices.CompositeUI;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using System.Threading;
using Jbe.TestSuite.Infrastructure.Interface.Services;
using Jbe.TestSuite.Infrastructure.Shell.Services;
using Jbe.TestSuite.Infrastructure.Shell.Properties;
using Jbe.TestSuite.Infrastructure.Library.Services;
using System.IO;

namespace Jbe.TestSuite.Infrastructure.Shell
{
    /// <summary>
    /// Main application entry point class.
    /// </summary>
    internal class ShellApplication : SmartClientApplication<WorkItem, ShellForm>
    {
        private static string[] Arguments;

        /// <summary>
        /// Application entry point.
        /// </summary>
        [STAThread]
        static void Main(string[] arguments)
        {
            Arguments = arguments;
#if (DEBUG)
            RunInDebugMode();
#else
            RunInReleaseMode();
#endif
        }

        protected override void AddServices()
        {
            base.AddServices();

            RootWorkItem.Services.AddNew<MessageService, IMessageService>();
            RootWorkItem.Services.AddNew<ShowAboutViewService, IShowAboutView>();

            ConfigureProfileCatalogModuleInfoStore();
        }

        protected virtual void ConfigureProfileCatalogModuleInfoStore()
        {
            ProfileCatalogModuleInfoStore moduleInfoStore =
                    (ProfileCatalogModuleInfoStore)RootWorkItem.Services.Get<IModuleInfoStore>(true);

            if (Arguments.Length > 0) { moduleInfoStore.CatalogFilePath = Arguments[0]; }

            if (!File.Exists(moduleInfoStore.CatalogFilePath))
            {
                throw new FileNotFoundException("The file '" + moduleInfoStore.CatalogFilePath + "' could not be found.");
            }
        }

        private static void RunInDebugMode()
        {
            SetVisualApplicationSettings();
            new ShellApplication().SplashRun(Resources.Splashscreen);
        }

        private static void RunInReleaseMode()
        {
            AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException;
            Application.ThreadException += ApplicationThreadException;
            
            SetVisualApplicationSettings();
            try
            {
                new ShellApplication().SplashRun(Resources.Splashscreen);
            }
            catch (Exception ex)
            {
                HandleException(ex, false);
            }
        }

        private static void AppDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            HandleException(e.ExceptionObject as Exception, e.IsTerminating);
        }

        private static void ApplicationThreadException(object sender, ThreadExceptionEventArgs e)
        {
            HandleException(e.Exception, false);
        }

        private static void HandleException(Exception ex, bool isTerminating)
        {
            if (ex == null) { return; }

            ExceptionPolicy.HandleException(ex, "Default Policy");

            if (!isTerminating)
            {
                MessageForm form = new MessageForm();
                form.MessageType = MessageType.Error;
                form.Message = Resources.UnknownError;
                form.Details = ex.ToString();
                form.ShowDialog();
                form.Dispose();
            }
        }

        private static void SetVisualApplicationSettings()
        {
            Application.SetCompatibleTextRenderingDefault(false);
            Application.EnableVisualStyles();

            ToolStripProfessionalRenderer r = new ToolStripProfessionalRenderer();
            r.ColorTable.UseSystemColors = true;
            ToolStripManager.Renderer = r;
        }
    }
}
